package com.xt.base.util;

import java.io.IOException;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import com.xt.base.acegi.AcegiUtils;
import com.xt.base.action.BaseAction;
import com.xt.base.dao.hibernate.HiberSessionHolder;
import com.xt.base.model.system.User;

public class UserInfoFilter implements Filter {

	// ----------------------------------------------------- Instance Variables

	// --------------------------------------------------------- Public Methods

	/**
	 * Take this filter out of service.
	 */
	public void destroy() {
	}

	/**
	 * 
	 * @param request
	 *            The servlet request we are processing
	 * @param result
	 *            The servlet response we are creating
	 * @param chain
	 *            The filter chain we are processing
	 * 
	 * @exception IOException
	 *                if an input/output error occurs
	 * @exception ServletException
	 *                if a servlet error occurs
	 */
	@SuppressWarnings("unchecked")
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpSession httpSession = ((HttpServletRequest) request).getSession();
		User user = (User) httpSession.getAttribute("currentUser");
		if (user == null) {
			String loginName = AcegiUtils.getUsername();
			if (StringUtils.isNotEmpty(loginName) && !"anonymousUser".equals(loginName)) {// 用户已通过ACEGI验证。
				Session hiberSession = HiberSessionHolder.getReadOnlySession();
				Criteria cir = hiberSession.createCriteria(User.class).add(
						Restrictions.eq("username", loginName));
				List users = cir.list();
				if (users != null && !users.isEmpty()) {// 成功取得用户信息
					user = (User) users.get(0);
					httpSession.setAttribute(BaseAction.SESSIONCURRENTUSER, user);
				}
				//HiberSessionHolder.clearSession();
			}
		}

		// Pass control on to the next filter
		chain.doFilter(request, response);

	}

	/**
	 * Place this filter into service.
	 * 
	 * @param filterConfig
	 *            The filter configuration object
	 */
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	// ------------------------------------------------------ Protected Methods

}
